package com.example.audiostreaming.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.audiostreaming.R;
import com.example.audiostreaming.activity.PlayerActivity;
import com.example.audiostreaming.adapters.AdapterTrackRv;
import com.example.audiostreaming.base.BaseFragment;
import com.example.audiostreaming.implement.HistoryPresenter;
import com.example.audiostreaming.implement.ImplPlayerLogic;
import com.example.audiostreaming.interfaces.IHistoryPresenterCallback;
import com.example.audiostreaming.views.ConfirmCheckBoxDialog;
import com.example.audiostreaming.views.ViewUILoader;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ximalaya.ting.android.opensdk.model.track.Track;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;

import static com.example.audiostreaming.base.BaseApplication.getAppContext;
import static com.example.audiostreaming.base.BaseApplication.getHandler;
import static com.ximalaya.ting.android.opensdk.util.Utils.getContext;

/**
 * 历史片段
 */
public class FragmentHistory extends BaseFragment {

    private ViewUILoader mUiLoader;
    private AdapterTrackRv mAdapterTrackRv;
    private HistoryPresenter mHistoryPresenter;
    private HistoryPresenterCallback mHistoryPresenterCallback;
    private Track mCurrentClickHistoryItem;

    @Override
    protected View onSubViewLoaded(final LayoutInflater layoutInflater, ViewGroup container) {
        FrameLayout subViewHistory = (FrameLayout) layoutInflater.inflate(R.layout.fragment_history, container, false);//获取历史子视图
        if (mUiLoader == null) {
            mUiLoader = new ViewUILoader(getAppContext()) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSussessView(layoutInflater,container);
                }

                @Override
                protected View getEmptyView() {
                    View emptyView = LayoutInflater.from(getContext()).inflate(R.layout.view_empty, this, false);
                    TextView emptyViewText = emptyView.findViewById(R.id.empty_view_text);
                    emptyViewText.setText("没有历史记录呢，赶紧去听节目吧！");
                    return emptyView;
                }
            };
        }else {
            if(mUiLoader.getParent() instanceof ViewGroup) {
                ((ViewGroup) mUiLoader.getParent()).removeView(mUiLoader);
            }
        }
        mHistoryPresenter = HistoryPresenter.getHistoryPresenter();
        mHistoryPresenterCallback = new HistoryPresenterCallback();
        mHistoryPresenter.registerViewCallback(mHistoryPresenterCallback);
//        mUiLoader.upDateStatus(ViewUILoader.UIStatus.LOADING);
//        getHandler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        },500);
        mHistoryPresenter.listHistories();
        subViewHistory.addView(mUiLoader);
        return subViewHistory;
    }

    private View createSussessView(LayoutInflater layoutInflater, ViewGroup container) {
        View successView = LayoutInflater.from(container.getContext()).inflate(R.layout.fragment_history_item, container, false);
        TwinklingRefreshLayout refreshLayout = successView.findViewById(R.id.over_scroll_view);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setEnableOverScroll(true);

        RecyclerView historyList = successView.findViewById(R.id.history_list);
        historyList.setLayoutManager(new LinearLayoutManager(container.getContext()));
        historyList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(),0);
                outRect.bottom = UIUtil.dip2px(view.getContext(),3);
                outRect.left = UIUtil.dip2px(view.getContext(),3);
                outRect.right = UIUtil.dip2px(view.getContext(),3);
            }
        });
        mAdapterTrackRv = new AdapterTrackRv();
        mAdapterTrackRv.setOnDetailAlbumItemClickListener(new AdapterTrackRv.OnDetailAlbumItemClickListener() {
            @Override
            public void onDetailAlbumItemClick(List<Track> detailAlbumListData, int position) {
                //设置播放器所需数据
                ImplPlayerLogic instanceImplPlayerLogic = ImplPlayerLogic.getInstanceImplPlayerLogic();
                instanceImplPlayerLogic.setPlayListData(detailAlbumListData,position);
                //跳转到播放器界面
                Intent intent = new Intent(getContext(), PlayerActivity.class);
                startActivity(intent);
            }
        });
        mAdapterTrackRv.setOnItemLongClickListener(new AdapterTrackRv.OnItemLongClickListener() {


            @Override
            public void onItemLongClick(Track track) {
                mCurrentClickHistoryItem = track;
                //去删除历史
                //Toast.makeText(getAppContext(),"删除历史："+track.getTrackTitle(),Toast.LENGTH_SHORT).show();
                ConfirmCheckBoxDialog dialog = new ConfirmCheckBoxDialog(getActivity());
                dialog.setOnDialogActionClickListener(new ConfirmCheckBoxDialog.OnDialogActionClickListener() {
                    @Override
                    public void onCancelClick() {
                        //不用做
                    }

                    @Override
                    public void onConfirmClick(boolean isCheck) {
                        //删除历史
                        if (mHistoryPresenter!=null && mCurrentClickHistoryItem != null) {
                            if (!isCheck) {
                                mHistoryPresenter.delHistory(mCurrentClickHistoryItem);
                            }else {
                                mHistoryPresenter.cleanHistories();
                            }
                        }
                    }
                });
                dialog.show();

            }
        });
        historyList.setAdapter(mAdapterTrackRv);
        return successView;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHistoryPresenter != null) {
            mHistoryPresenter.unRegisterViewCallback(mHistoryPresenterCallback);
            mHistoryPresenter = null;
        }
    }

    private class HistoryPresenterCallback implements IHistoryPresenterCallback {
        @Override
        public void onHistoriesLoaded(List<Track> tracks) {
            if (tracks==null||tracks.size()==0) {
                mUiLoader.upDateStatus(ViewUILoader.UIStatus.EMPTY);
            }else {
                //更新数据
                mAdapterTrackRv.setData(tracks);
                mUiLoader.upDateStatus(ViewUILoader.UIStatus.SUCCESS);
            }
        }
    }
}
